import { createStore } from 'vuex'

export default createStore({
  state: {
    userInfo: null,
    token: localStorage.getItem('token') || ''
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = null
      state.token = ''
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 登录
    async login({ commit }, loginForm) {
      try {
        // TODO: 调用后端登录接口
        const response = { data: { token: 'dummy-token', userInfo: { username: loginForm.username } } }
        commit('SET_TOKEN', response.data.token)
        commit('SET_USER_INFO', response.data.userInfo)
        return Promise.resolve(response.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER_INFO')
    }
  }
}) 